import { ref, watch, onUnmounted, readonly } from 'vue'
import { useBookDataStore } from '../stores/book-data'
import { bookService } from '../services/book-service'
import type { Chapter, Character, Location, Inspiration } from '../stores/book-data'

// 自动保存配置
interface AutoSaveConfig {
  enabled: boolean
  interval: number // 保存间隔，毫秒
  debounceTime: number // 防抖时间，毫秒
}

// 自动保存状态
interface AutoSaveState {
  isSaving: boolean
  lastSaveTime: Date | null
  hasUnsavedChanges: boolean
  saveError: string | null
}

// 自动保存队列项
interface AutoSaveItem {
  type: 'chapter' | 'character' | 'location' | 'inspiration'
  id: number | null
  data: Chapter | Character | Location | Inspiration
  timestamp: number
}

export function useAutoSave(config: Partial<AutoSaveConfig> = {}) {
  // 默认配置
  const defaultConfig: AutoSaveConfig = {
    enabled: true,
    interval: 30000, // 30秒
    debounceTime: 2000 // 2秒
  }

  // 合并配置
  const finalConfig = { ...defaultConfig, ...config } as AutoSaveConfig

  // 状态
  const autoSaveState = ref<AutoSaveState>({
    isSaving: false,
    lastSaveTime: null,
    hasUnsavedChanges: false,
    saveError: null
  })

  // 保存队列
  const saveQueue = ref<AutoSaveItem[]>([])
  
  // 定时器引用
  let saveTimer: NodeJS.Timeout | null = null
  let debounceTimer: NodeJS.Timeout | null = null

  // 获取store
  const bookDataStore = useBookDataStore()

  // 添加到保存队列
  function addToSaveQueue<T extends Chapter | Character | Location | Inspiration>(
    type: AutoSaveItem['type'],
    data: T
  ) {
    if (!finalConfig.enabled) return

    const item: AutoSaveItem = {
      type,
      id: data.id || null,
      data,
      timestamp: Date.now()
    }

    // 检查是否已存在相同类型的项
    const existingIndex = saveQueue.value.findIndex(
      q => q.type === type && (q.id === item.id || (q.id === null && item.id === null))
    )

    if (existingIndex !== -1) {
      // 更新现有项
      saveQueue.value[existingIndex] = item
    } else {
      // 添加新项
      saveQueue.value.push(item)
    }

    // 标记有未保存的更改
    autoSaveState.value.hasUnsavedChanges = true

    // 重置防抖定时器
    if (debounceTimer) {
      clearTimeout(debounceTimer)
    }

    // 设置防抖定时器
    debounceTimer = setTimeout(() => {
      processSaveQueue()
    }, finalConfig.debounceTime)
  }

  // 处理保存队列
  async function processSaveQueue() {
    if (!finalConfig.enabled || saveQueue.value.length === 0 || autoSaveState.value.isSaving) {
      return
    }

    autoSaveState.value.isSaving = true
    autoSaveState.value.saveError = null

    // 复制队列并清空原队列
    const itemsToSave = [...saveQueue.value]
    saveQueue.value = []

    try {
      // 逐个保存
      for (const item of itemsToSave) {
        await saveItem(item)
      }

      // 更新状态
      autoSaveState.value.lastSaveTime = new Date()
      autoSaveState.value.hasUnsavedChanges = saveQueue.value.length > 0
    } catch (error) {
      console.error('自动保存失败:', error)
      autoSaveState.value.saveError = String(error)
      
      // 重新加入队列
      saveQueue.value.unshift(...itemsToSave)
    } finally {
      autoSaveState.value.isSaving = false
    }
  }

  // 保存单个项
  async function saveItem(item: AutoSaveItem) {
    switch (item.type) {
      case 'chapter':
        if (item.id) {
          await bookService.updateChapter(item.data as Chapter)
        } else {
          await bookService.createChapter(item.data as Chapter)
        }
        break
      case 'character':
        if (item.id) {
          await bookService.updateCharacter(item.data as Character)
        } else {
          await bookService.createCharacter(item.data as Character)
        }
        break
      case 'location':
        // 位置信息作为章节的一部分保存，不需要单独的API
        console.log('Location data saved as part of chapter:', item.data)
        break
      case 'inspiration':
        if (item.id) {
          await bookService.updateInspiration(item.data as Inspiration)
        } else {
          await bookService.createInspiration(item.data as Inspiration)
        }
        break
    }
  }

  // 手动触发保存
  async function saveNow() {
    await processSaveQueue()
  }

  // 清除队列
  function clearQueue() {
    saveQueue.value = []
    autoSaveState.value.hasUnsavedChanges = false
  }

  // 启用/禁用自动保存
  function setEnabled(enabled: boolean) {
    finalConfig.enabled = enabled
    if (!enabled) {
      clearQueue()
      if (saveTimer) {
        clearInterval(saveTimer)
        saveTimer = null
      }
    } else {
      startAutoSaveTimer()
    }
  }

  // 启动自动保存定时器
  function startAutoSaveTimer() {
    if (saveTimer) {
      clearInterval(saveTimer)
    }

    saveTimer = setInterval(() => {
      if (saveQueue.value.length > 0 && !autoSaveState.value.isSaving) {
        processSaveQueue()
      }
    }, finalConfig.interval)
  }

  // 监听store变化
  watch(
    () => [
      bookDataStore.chapters,
      bookDataStore.characters,
      bookDataStore.locations,
      bookDataStore.inspirations
    ],
    () => {
      // 这里可以添加更精细的变化检测逻辑
      // 目前简化处理，由具体组件调用addToSaveQueue
    },
    { deep: true }
  )

  // 组件卸载时清理
  onUnmounted(() => {
    if (saveTimer) {
      clearInterval(saveTimer)
    }
    if (debounceTimer) {
      clearTimeout(debounceTimer)
    }
  })

  // 启动定时器
  if (finalConfig.enabled) {
    startAutoSaveTimer()
  }

  return {
    // 状态
    autoSaveState: readonly(autoSaveState),
    
    // 方法
    addToSaveQueue,
    saveNow,
    clearQueue,
    setEnabled
  }
}